# -*- coding: utf-8 -*-
"""
Created on Wed Apr 24 10:25:28 2024

@author: 刘翼
"""

import cv2
import numpy as np

img = cv2.imread(r"C:\Users\Public\opencv\Figure\contours2.png") 
cv2.imshow("original",img) 
gray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)  

ret, binary = cv2.threshold(gray,127,255,cv2.THRESH_BINARY)  
contours, hierarchy = cv2.findContours(binary,cv2.RETR_LIST,cv2.CHAIN_APPROX_SIMPLE)  

n=len(contours)
contoursImg=[]
for i in range(n):
    temp=np.zeros(img.shape,np.uint8)
    contoursImg.append(temp)
    contoursImg[i]=cv2.drawContours(contoursImg[i],contours,i, (0,255,255) ,3) 
    cv2.imshow("contours[" + str(i)+"]",contoursImg[i]) 

print("各轮廓的矩（moments）如下：")
for i in range(n):
	print("轮廓"+str(i)+"的矩:\n",cv2.moments(contours[i]))

print("各轮廓的面积如下：")
for i in range(n):
	print("轮廓"+str(i)+"的面积:%d" %cv2.moments(
contours[i])['m00'])

cv2.waitKey(0)
cv2.destroyAllWindows()
